package filters;

import com.alibaba.fastjson.JSON;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        所有的请求都会到这里来，有些请求是不需要经过检查，直接放行：访问登录servlet,发放凭证
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        String[] urls={"/api/bookById","/api/getBooks","/api/category","/api/hotBooks","/api/getNotice","/api/activeUser","/api/register","/api/login",".ico",".jpg",".html"};
        //不需要登录就可以访问的接口放行清单,请求地址中出现这样的单词就放行
        String url=request.getRequestURL().toString();
        System.out.println(request.getRequestURL());
        boolean tag=false;
        for(String u :urls){
            if(url.indexOf(u)>0){
                tag=true;
                break;
            }
        }
//        其他请求都需要经过检查，检查方法如下：
//        第一步，根据携带id，获取对应的session,
        if(tag==false){
            HttpSession session=request.getSession();
//        第二步：检查里面是否有user这个键,
            if(session.getAttribute("user")==null){//如果没有这个键，则直接拦截返回还没有登录消息
                Response build=Response.build(ResponseCode.NOT_LOGIN);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSON(build).toString());
            }else{//在前面近端时间登陆过，直接放行，访问后面的资源
                filterChain.doFilter(request,response);
            }
        }else {//有这个键，表示曾经登录过，还没有过期，放行，
            System.out.println("放行");
            filterChain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }
}
